<template>
  <div class="add-comment-container">
    <el-avatar :size="40" :src="userAvatar">
      <el-icon><User /></el-icon>
    </el-avatar>
    <div class="comment-input-area">
      <el-input
        ref="commentInputRef"
        v-model="commentContent"
        type="textarea"
        :rows="isFocused ? 3 : 1"
        :placeholder="placeholderText"
        @focus="handleFocus"
        @blur="handleBlur"
        resize="none"
        class="comment-textarea"
      />
      <div v-if="isFocused || commentContent" class="comment-actions">
        <!-- 可以添加表情选择、@用户等功能 -->
        <el-button type="primary" @click="submitComment" :loading="submitting" :disabled="!isLoggedIn || !commentContent.trim()">
          {{ parentId ? '回复' : '评论' }}
        </el-button>
        <el-button @click="cancelComment" v-if="isFocused">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';
import { useStore } from 'vuex';
import axios from '@/services/axios'
import { ElMessage } from 'element-plus';
import { User } from '@element-plus/icons-vue';

const props = defineProps({
  targetId: {
    type: String,
    required: true
  },
  targetType: {
    type: String,
    required: true, // 'video' or 'post'
    validator: (value) => ['video', 'post'].includes(value)
  },
  parentId: {
    type: String, // 如果是回复评论，则传入父评论 ID
    default: null
  },
  replyToUser: { // 回复哪个用户，用于 placeholder
      type: Object,
      default: null
  }
});

const emit = defineEmits(['comment-added', 'cancel-reply']); // 添加 cancel-reply 事件

const store = useStore();
const commentContent = ref('');
const submitting = ref(false);
const isFocused = ref(false);
const commentInputRef = ref(null); // 用于聚焦

// 提供聚焦方法给父组件使用
const focusInput = () => {
  const textarea = commentInputRef.value?.$el.querySelector('textarea');
  if (textarea) {
    textarea.focus();
  }
};

// 检查用户登录状态
const isLoggedIn = computed(() => store.getters['auth/isAuthenticated']);

// 安全地获取用户信息
const currentUser = computed(() => {
  try {
    return store.state.user.profile || null;
  } catch (error) {
    console.warn('Failed to get user profile:', error);
    return null;
  }
});

// 安全地获取用户头像
const userAvatar = computed(() => {
  if (!isLoggedIn.value) return null;
  return currentUser.value?.avatar || null;
});

const placeholderText = computed(() => {
  if (!isLoggedIn.value) return '请登录后发表评论';
  if (props.parentId && props.replyToUser) {
    return `回复 @${props.replyToUser.username}`;
  }
  return '添加评论...';
});

const handleFocus = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    return;
  }
  isFocused.value = true;
};

const handleBlur = () => {
  // 延迟处理，以便按钮点击事件能触发
  setTimeout(() => {
    // 如果输入框为空，并且不是回复状态（回复状态下即使失焦也保持展开），则收起
    if (!commentContent.value && !props.parentId) {
      isFocused.value = false;
    }
  }, 200);
};

const submitComment = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    return;
  }

  if (!commentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }

  submitting.value = true;
  try {
    const payload = {
      text: commentContent.value.trim(),
      targetType: props.targetType,
      targetId: props.targetId
    };

    // 只在有父评论时添加 parentId
    if (props.parentId) {
      payload.parentId = props.parentId;
    }
    
    const response = await axios.post('/api/comments', payload);
    
    // 清空输入框并重置状态
    commentContent.value = '';
    isFocused.value = false;

    // 触发评论添加成功事件
    emit('comment-added', response.data.comment);

    ElMessage.success(props.parentId ? '回复成功' : '评论成功');
  } catch (error) {
    console.error('提交评论失败:', error);
    ElMessage.error(error.response?.data?.error || '评论提交失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};

const cancelComment = () => {
  commentContent.value = '';
  isFocused.value = false;
  if (props.parentId) {
    emit('cancel-reply');
  }
};

// 在 script setup 末尾添加
defineExpose({
  focusInput
});
</script>

<style scoped>
.add-comment-container {
  display: flex;
  align-items: flex-start; /* 头像和输入框顶部对齐 */
  margin-bottom: 20px;
}

.user-avatar {
  margin-right: 12px;
  flex-shrink: 0; /* 防止头像被压缩 */
}

.comment-input-area {
  flex: 1;
}

.comment-textarea :deep(.el-textarea__inner) {
  padding: 8px 12px;
  line-height: 1.5;
  border: none;
  border-bottom: 1px solid #dcdfe6;
  border-radius: 0;
  box-shadow: none;
  transition: border-color 0.3s, height 0.2s ease-out;
}

.comment-textarea :deep(.el-textarea__inner:focus) {
  border-bottom: 2px solid #409EFF;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.comment-actions .el-button {
  margin-left: 8px;
}
</style>